﻿using AutoMapper;
using D.Medicalcare.Domain.Entities;
using D.Medicalcare.ErrorCode;
using D.Medicalcare.Infrastructure.Interfaces;
using D.Medicalcare.Write.API.Application.Commands.PatientCommand;
using MediatR;

namespace D.Medicalcare.Write.API.Application.Handlers.PatientHandler
{
    /// <summary>
    /// 添加就诊人处理
    /// </summary>
    public class CreatePatientHandler : IRequestHandler<CreatePatientCommand, APIResult<object>>
    {
        private readonly IMapper mapper;
        private readonly IBaseRepository<Patient> prep;
        private readonly ILogger<CreatePatientHandler> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mapper">映射</param>
        /// <param name="prep">仓储</param>
        /// <param name="logger">日志</param>
        public CreatePatientHandler(IMapper mapper,IBaseRepository<Patient> prep,ILogger<CreatePatientHandler> logger)
        {
            this.mapper = mapper;
            this.prep = prep;
            this.logger = logger;
        }
        /// <summary>
        /// 处理
        /// </summary>
        public Task<APIResult<object>> Handle(CreatePatientCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            try
            {
                var map=mapper.Map<Patient>(request);
                var m = prep.GetAll().Where(x => x.DocumentNo == request.DocumentNo).Count();
                if (m > 0)
                {
                    result.Code = APIEnum.Failed;
                    result.Msg = "身份证号不可重复，请重新输入";

                }
                else
                {
                    var a = prep.AddAsync(map).Result;
                    var model = prep.GetAll().FirstOrDefault(x => x.DocumentNo == request.DocumentNo);
                        if (a > 0)
                        {
                            result.Code = APIEnum.Success;
                            result.Msg = "添加成功";
                            result.Data = model;
                            logger.LogInformation("添加就诊人成功");
                        }
                        else
                        {
                            result.Code = APIEnum.Failed;
                            result.Msg = "添加失败";
                            result.Data = model;
                            logger.LogError("添加就诊人失败");
                        }
                }
                
                return Task.FromResult(result);
            }
            catch (Exception ex)
            {
                logger.LogError("添加就诊人异常"+ex.Message);
                throw;
            }
        }
    }
}
